package com.qiao.glod.util;

import android.util.SparseArray;

import com.qiao.glod.api.ICallback;

import java.util.ArrayList;

/**
 * Created by Qiao on 2016/4/17.
 * function：
 */
public class LocalRequestManager {
    private static final String TAG = "LocalRequestManager";

    private final SparseArray<ArrayList<ICallback>> mCallBacks
            = new SparseArray<>();

    private static final Object mLock = new Object();
    static LocalRequestManager mInstance;
    public static LocalRequestManager getInstance() {
        synchronized (mLock) {
            if (mInstance == null) {
                mInstance = new LocalRequestManager();
            }
            return mInstance;
        }
    }

    public boolean isNewRequest(int key,ICallback callback){
        ArrayList<ICallback> callbacks = mCallBacks.get(key);
        if(callbacks == null){
            callbacks = new ArrayList<>();
            if(callback!=null) callbacks.add(callback);
            mCallBacks.put(key,callbacks);
            return true;
        }else{
            if(callback!=null) callbacks.add(callback);
        }
        return false;
    }

    public void callback(int key,Object obj){
        ArrayList<ICallback> callbacks = mCallBacks.get(key);
        if(callbacks != null){
            for (ICallback callback:callbacks) {
                callback.onSuccess(obj);
            }
            mCallBacks.remove(key);
        }
    }

    public void callback(int key,String message){
        ArrayList<ICallback> callbacks = mCallBacks.get(key);
        if(callbacks != null){
            for (ICallback callback:callbacks) {
                callback.onFailed(message);
            }
            mCallBacks.remove(key);
        }
    }
}
